
<?php 
	$dialogId = "DialogAddAnswer";
	$messageErrorId = "messageErrorId";
?>

<div class="box_mid" id="<?= $dialogId?>" title="Add answer">
	<?php echo $this->Session->flash(); ?>
	<?php echo "<div id='$messageErrorId'></div>";?>
	<div class="box_mid_content">
		<div class="box_mid_content_top">
		</div>
		<div class="box_mid_content_mid">
		<?php $idCkeditor = 'Content'.$question_id ;?>
		<?= $this->Form->create('Answer')?>
			<div class="info">
				<?= $this->Form->input('correct',array('id' => 'correct'.$question_id, 'value' => '0'))?>
			</div>
			<?= $this->Form->input('content', array('id'=>$idCkeditor));?>
			<?= $this->CKEditor->load($idCkeditor) ?>
			<?= $this->Form->end(); ?>
		</div>
	</div>
	<div id="temp"></div>
</div>

<script type="text/javascript">

	function ShowAnswerById(answer_id, div_id) {
		$.ajax({
			async:true,
			url: "../answers/Show/"+answer_id,
			beforeSend:function(request){

			},
			complete:function(request, json){
				html = '<li>'+request.responseText+'</li>';
				$('#'+div_id).append(html);
			}  
		});
	}

	$(function() {	
		$( "#<?= $dialogId ?>" ).dialog( "destroy" );
		var correct = $("#correct" + "<?= $question_id?>");
		
		$("#<?= $dialogId ?>").dialog({
			autoOpen: true,
			modal: true,
			bgiframe: true,
			height: 600,
			width: 1000,
			title: "Add answer" ,
			show: { effect: 'drop', direction: "up" },
			hide: { effect: 'drop', direction: "down" },
			buttons: [
						{
						    text: "Save",
						    click: function(){
						    	var answerContent_data = CKEDITOR.instances["<?= $idCkeditor?>"].getData();
								$.ajax({
									async:true,
									dataType: "Json",
									url: "../answers/AddAnswerByJson",
									data: {
										'question_id' : <?= $question_id ?>,
										'correct': correct.is(':checked'),
										'content': answerContent_data
									},
									beforeSend:function(request){

									},
									complete:function(request, json){
										if(json == 'success'){
											var dataResult = JSON.parse(request.responseText);

											if (dataResult['status']) {
												$('#<?= $dialogId ?>').dialog("close");
												ShowAnswerById(dataResult['answerId'], 'container-answers-<?= $question_id?>');
											}else{
												var messages = "<div class='error-message'>"+dataResult['message']+"</div>";
												$("#<?= $messageErrorId ?>").html(messages);
			
											}
										}
									}  
								});
						    }
						 },
						{
							text: "Close",
							click: function(){
								$(this).dialog("close");
							}
						}
					],
				close: function(){
					$('#<?= $dialogId ?>').remove();
					$('.ui-effects-wrapper').remove();
				}
		});
	});
</script>